package com.cn.dao.impl;

import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.cn.dao.CartDao;
import com.cn.domain.Cart;
import com.cn.utils.DBUtils;

public class CartDaoImpl implements CartDao{
	//插入购物信息到购物车
	public int addCart(Cart cart) {
		int i=0;
		try {
			Object[] params= {cart.getPid(),cart.getQuantity(),cart.getUserid()};
			i=DBUtils.getQuryRunner().update("insert into HWUA_CART(ID,PID,QUANTITY,USERID) values(SEQ_CART.nextval,?,?,?)",params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return i;
	}
	
	//根据所有的购物表中的信息显示到购物车上
	public List<Cart> queryAllCart(long userId) {
		List<Cart> list=null;
		try {
			Object[] params= {userId};
			list=DBUtils.getQuryRunner().query("select * from HWUA_CART where USERID=?",new BeanListHandler<Cart>(Cart.class),params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	
	//根据商品ID更新商品数量
	@Override
	public int updateCartById(long num,long id,long userId){
		int i=0;
		try {
			Object[] params= {num,id,userId};
			i=DBUtils.getQuryRunner().update("update HWUA_CART set QUANTITY=? where PID=? and USERID=?",params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return i;
	}
	//根据商品ID查询购物记录，这个用于查询一下购物车是否存在该条记录，
	//有就可以直接跟新，没有就进行插入
	@Override
	public Cart queryCartById(long pid,long userId){
		Cart cart=null;
		try {
			Object[] params= {pid,userId};
			cart=DBUtils.getQuryRunner().query("select * from HWUA_CART where PID=? and USERID=?",new BeanHandler<Cart>(Cart.class),params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return cart;
	}

	@Override
	public int delCartByPidAndUserId(long pid, long userId) {
		int i=0;
		try {
			Object[] params= {pid,userId};
			i=DBUtils.getQuryRunner().update("delete from HWUA_CART where PID=? and USERID=?",params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return i;
	}
}
